package com.xcdh.orm.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.xcdh.commons.utils.DataSourceContextHolder;
import com.xcdh.orm.entity.OrmDataSource;
import com.xcdh.orm.util.DBServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {

    private Map<Object, Object> targetDataSources = new HashMap<>();
    @Autowired
    @Lazy
    private DataSourceCache dataSourceCache ;
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.get();//实现切换
    }



//  数据源放入
    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.targetDataSources = targetDataSources ;
        // 同步到resolvedDataSources中
        super.afterPropertiesSet();
    }

    public boolean isExistsConnection(Object serviceKey){
        return targetDataSources.containsKey(serviceKey) ;
    }

    public void setDefaultTargetDataSource(DruidDataSource defaultTargetDataSource) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
    }

    @Override
    protected DataSource determineTargetDataSource() {
        Object lookupKey = determineCurrentLookupKey();
        if(lookupKey == null ){
            return super.getResolvedDefaultDataSource() ;
        }
        OrmDataSource dataSource = dataSourceCache.getDataSource((String) lookupKey);
        if(dataSource == null){
            throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
        }
        return DBServiceUtil.createDs(dataSource) ;
    }


}
